package dl.jf.web.action;

import javax.servlet.http.Cookie;

import org.apache.struts2.interceptor.validation.SkipValidation;


import dl.jf.common.constants.Constants;
import dl.jf.service.iservice.ILoginService;
import dl.jf.web.form.MainForm;
import dl.jf.web.util.Toolkit;
public class LoginAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -232017348344100732L;

	public LoginAction() {
		super("LoginAction");
	}

	// login
	private String userId;
	private String password;

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	// form
	private MainForm mainForm;

	public MainForm getMainForm() {
		return mainForm;
	}

	public void setMainForm(MainForm mainForm) {
		this.mainForm = mainForm;
	}

	// service
	private ILoginService loginService;
	public void setLoginService(ILoginService loginService) {
		this.loginService = loginService;
	}

	@Override
	public String execute() throws Exception {
		if (!Toolkit.isEmpty(getUserId()) && !Toolkit.isEmpty(getPassword())) {
			return doLogin();
		} else {
			return Constants.ACTION_RESULT_TO_LOGIN;
		}
	}

	public String doLogin() throws Exception {
		if (Toolkit.isEmpty(getUserId()) || Toolkit.isEmpty(getPassword())) {
			return Constants.ACTION_RESULT_TO_LOGIN;
		}

		if (loginService.valid(getUserId(), getPassword())) {
			session.put("userId", getUserId());
			// session.put("password", getPassword());
			session.put(Constants.LOGIN_SUCCESS, "true");
			Cookie c = new Cookie("user", getUserId());
			c.setMaxAge(60 * 60);
			// response.addCookie(c);
			return SUCCESS;
		} else {
			return ERROR;
		}
	}
}
